<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" v-loading="formLoading">
      <el-form-item label="实践点名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入实践点名称" />
      </el-form-item>
      <el-form-item label="归属地" prop="districtId">
        <el-tree-select
          v-model="formData.districtId"
          :data="deptList"
          :props="defaultProps"
          node-key="id"
          placeholder="请选择归属地" />
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="联系人" prop="contact">
            <el-input v-model="formData.contact" placeholder="请输入联系人" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系人号码" prop="contactNumber">
            <el-input v-model="formData.contactNumber" type="text" placeholder="请输入联系人号码" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="开放时间" prop="openTime">
        <el-input v-model="formData.openTime" placeholder="开放时间" />
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="16">
          <el-form-item label="地址" prop="address">
            <el-input v-model="formData.address" placeholder="请输入地址"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label-width="0" prop="location">
            <el-input :value="formData.location" disabled placeholder="请标记坐标">
              <template #append>
                <el-button icon="ep:location" @click="handleOpenMap" />
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="VR地址" prop="vrAddress">
        <el-input v-model="formData.vrAddress" placeholder="请输入VR地址" />
      </el-form-item>

      <el-form-item label="宣传照片" prop="photoUrl">
        <UploadImgs v-model="formData.photoUrl" class="min-w-80px" />
      </el-form-item>
      <el-form-item label="简介" prop="description">
        <Editor v-model="formData.description" height="150px" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <el-dialog
class="dialog companygoodsLog" v-model="mapVisible" :close-on-click-modal="false" :draggable="true"
    :show-close="false" title="位置选择" destroy-on-close style="border-radius: 4px;background-color: #ffffff" top="100px"
    width="80%">
    <div style="height:40px;width:100%;display: flex;align-items: center;">
      <el-select
        v-model="areaValue"
        filterable
        style='width:350px' remote reserve-keyword placeholder="请输入关键词"
        :remote-method="remoteMethod" :loading="loading" @change="currentSelect">
        <el-option v-for="item in areaList" :key="item.id" :label="item.name" :value="item" class="one-text">
          <span style="float: left">{{ item.name }}</span>
          <span style="float: right; color: #8492a6; font-size: 13px">{{
            item.district
          }}</span>
        </el-option>
      </el-select>
    </div>
    <div id="container" style="height:500px;width:100%;margin-top:10px;"></div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCloseMap">关闭</el-button>
        <el-button type="primary" @click="confirmData">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { SpotApi, SpotVO } from '@/api/scenic/spot'
import * as DeptApi from '@/api/system/dept'
import { defaultProps, handleTree } from '@/utils/tree';
import AMapLoader from "@amap/amap-jsapi-loader";

window._AMapSecurityConfig = {
  // 安全密钥
  securityJsCode: "b64d07fbb6f39bb23e0605688d17c6aa",
}

/** 实践点 表单 */
defineOptions({ name: 'SpotForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const mapVisible = ref(false)
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  name: undefined,
  description: undefined,
  contact: undefined,
  contactNumber: undefined,
  openTime: undefined,
  districtId: undefined,
  lnt: undefined,
  lat: undefined,
  photoUrl: [],
  location: '',
  address: '',
  vrAddress: ''
})
const formRules = reactive({
  name: [{ required: true, message: '实践点名称不能为空', trigger: 'blur' }],
  districtId: [{ required: true, message: '归属地不能为空', trigger: 'blur' }],
  contact: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
  contactNumber: [{ required: true, message: '联系人号码不能为空', trigger: 'blur' },],
  openTime: [{ required: true, message: '开放时间不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
const deptList = ref<Tree[]>([]) // 树形结构
const areaValue = ref('')
let map: any = null
let aMap: any = null
let AutoComplete: any = null
const loading: any = ref(false)
const areaList: any = ref([])
let geoCoder: any = null
const checkedForm: any = ref()
let deptListResult: any[] = []

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await SpotApi.getSpot(id)
      formData.value.location = `${formData.value.lnt || ''}${formData.value.lat || ''}`
      formData.value.photoUrl = (formData.value.photoUrl || '').split(',').filter(item => item)
      formData.value.description = formData.value.description || undefined
    } finally {
      formLoading.value = false
    }
  }
  // 加载部门树
  deptListResult = await DeptApi.getSimpleDeptList()
  deptList.value = handleTree(deptListResult)
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  console.log(formData.value)
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = { ...formData.value as unknown as SpotVO}
    data.cityId = deptListResult.find(item => item.id === data.districtId)?.parentId
    data.provinceId = 100
    data.photoUrl = (data.photoUrl || []).join(',')
    if (formType.value === 'create') {
      await SpotApi.createSpot(data)
      message.success(t('common.createSuccess'))
    } else {
      await SpotApi.updateSpot(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    description: undefined,
    contact: undefined,
    contactNumber: undefined,
    openTime: undefined,
    districtId: undefined,
    lnt: undefined,
    lat: undefined,
    photoUrl: [],
    location: '',
    address: '',
    vrAddress: ''
  }
  formRef.value?.resetFields()
}

const handleOpenMap = () => {
  initMap();
  mapVisible.value = true
}

const initMap = () => {
  AMapLoader.load({
    key: "7587e7c6bc999c1d36bbe863b52249a7", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ["AMap.Geocoder", "AMap.AutoComplete"], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
  }).then((AMap: any) => {
    aMap = AMap
    map = new AMap.Map("container", {
      // 设置地图容器id
      viewMode: "3D", // 是否为3D地图模式
      zoom: 11, // 初始化地图级别
      // center: [116.397428, 39.90923], // 初始化地图中心点位置
      center: [formData.value.lnt || 116.397428, formData.value.lat || 39.90923]
    });
    if(formData.value.location) {
      addmark(formData.value.lnt, formData.value.lat, AMap)
    }
    AutoComplete = new AMap.AutoComplete({
      city: '全国',
    });
    geoCoder = new AMap.Geocoder({
      city: "010", //城市设为北京，默认：“全国”
      radius: 1000, //范围，默认：500
    });
    map.on('click', (e: any) => {
      addmark(e.lnglat.getLng(), e.lnglat.getLat(), AMap)
    })
  })
    .catch((e) => {
      console.log(e);
    });
}
let marker: any = null
const addmark = (lat: any, lng: any, AMap: any) => {
  marker && removeMarker()
  marker = new AMap.Marker({
    position: new AMap.LngLat(lat, lng),
    title: '北京',
    zoom: 13
  });
  checkedForm.value = {
    lat: lng,
    lng: lat,
  }
  map.add(marker);
  map.setCenter([lat, lng], '', 500);
}

const removeMarker = () => {
  map.remove(marker)
}

const remoteMethod = (searchValue: any) => {
  if (searchValue !== "") {
    setTimeout(() => {
      AutoComplete.search(searchValue, (status: any, result: any) => {
        console.log(result, status)
        if (result.tips?.length) {
          areaList.value = result?.tips
        }
      });
    }, 200);
  } else {

  }
}

const currentSelect = (val: any) => {
  checkedForm.value = {
    lat: val.location?.lat,
    lng: val.location?.lng,
  }
  addmark(val.location?.lng, val.location?.lat, aMap)
  map.setCenter([val.location?.lng, val.location?.lat], '', 500);
}

const confirmData = () => {
  if (!checkedForm.value?.lat || !checkedForm.value?.lng) {
    return ElMessage.error('请选择地址')
  }
  formData.value.lnt = checkedForm.value?.lng
  formData.value.lat = checkedForm.value?.lat
  formData.value.location = `${checkedForm.value?.lng},${checkedForm.value?.lat}`
  mapVisible.value = false
  areaValue.value = ''
  map?.destroy();
}

const handleCloseMap = () => {
  mapVisible.value = false
  areaValue.value = ''
  map?.destroy();
}
</script>
